package com.egoo.ticket.server.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.egoo.ticket.server.dao.*;
import com.egoo.ticket.server.pojo.dto.WorkOrderTriggerInfoDto;
import com.egoo.ticket.server.pojo.entity.EwsUser;
import com.egoo.ticket.server.pojo.entity.WorkOrderTriggerInfo;
import com.egoo.ticket.server.pojo.vo.*;
import com.egoo.ticket.server.service.*;
import com.egoo.ticket.server.utils.common.ConstantCode;
import com.egoo.ticket.server.utils.common.CreateCodeUtil;
import com.egoo.ticket.server.utils.common.DbResponse;
import com.egoo.ticket.server.utils.common.ResponseConstant;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author：victor_tang
 * @Date ：2020/1/6
 * @Description：工单触发器实现类
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class WorkOrderTriggerInfoServiceImpl implements WorkOrderTriggerInfoService {

	@Autowired
	private WorkOrderTriggerInfoDao workOrderTriggerInfoDao;
	@Autowired
	private WorkOrderTriggerRelationDao workOrderTriggerRelationDao;

	@Autowired
	private EwsUserDao ewsUserDao;

	@Autowired
	private EwsRoleDao ewsRoleDao;

	@Autowired
	private SysDictDao sysDictDao;

	@Autowired
	private WorkOrderTypeDao workOrderTypeDao;

	@Autowired
	private WorkOrderStatusDao workOrderStatusDao;

	@Autowired
	private CustomFieldService customFieldService;

	@Autowired
	private WorkOrderFilterMenuService workOrderFilterMenuService;

	@Autowired
	private WorkOrderFieldReflectService workOrderFieldReflectService;

	@Autowired
	private DepartmentService departmentService;
	@Autowired
	private CreateCodeUtil createCodeUtil;
	@Autowired
	private EripDataSynService eripDataSynService;
	/**
	 * TODO 获取工单触发器列表
	 *
	 * @param workOrderTriggerInfoDto 1
	 * @author: victor_tang
	 * @createtime: 2020/1/6 13:50
	 * @return: java.utils.List<com.egoo.ews.service.vo.WorkOrderTriggerInfoVo>
	 */
	@Override
	public DbResponse getListBycondition(WorkOrderTriggerInfoDto workOrderTriggerInfoDto) {
		// 设置分页参数
		PageHelper.startPage(workOrderTriggerInfoDto.getPage(), workOrderTriggerInfoDto.getPageSize());

		List<WorkOrderTriggerInfoVo> dataList =
				workOrderTriggerInfoDao.selectByCondition(workOrderTriggerInfoDto);

		PageInfo<WorkOrderTriggerInfoVo> pageInfo = new PageInfo<>(dataList);

		return new DbResponse(ResponseConstant.RES_SUCCESS_CODE,
				ResponseConstant.SELECT_SUCCESS_MSG, dataList, pageInfo.getTotal());
	}

	/**
	 * TODO 新增工单触发器
	 *
	 * @param workOrderTriggerInfo 1
	 * @author: victor_tang
	 * @createtime: 2020/1/6 13:50
	 * @return: com.egoo.ews.service.utils.DBResponse
	 */
	@Override
	public DbResponse addSave(WorkOrderTriggerInfo workOrderTriggerInfo) {

		EwsUser ewsUser = ewsUserDao.selectById(workOrderTriggerInfo.getCreateUserId());
		if (ewsUser == null) {
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,
					"未找到该创建人用户信息！");
		}
		JSONObject triggerCondition = handleTriggerCondition(workOrderTriggerInfo.getTriggerCondition());
		workOrderTriggerInfo.setTriggerCondition(triggerCondition);
		workOrderTriggerInfo.setId(createCodeUtil.getTriggerId());
		workOrderTriggerInfo.setCreateUserName(ewsUser.getName());
		workOrderTriggerInfo.setCreateTime(new Date());
		workOrderTriggerInfo.setUpdateTime(new Date());
		workOrderTriggerInfo.setDeleted(ConstantCode.DELETE_NOMAL);

		int result = workOrderTriggerInfoDao.insertSelective(workOrderTriggerInfo);


			return new DbResponse(ResponseConstant.RES_SUCCESS_CODE, ResponseConstant.ADD_SUCCESS_MSG);

	}
	/**
	 * TODO 处理触发器条件内容
	 * @author: victor_tang
	 * @createtime: 2020/1/15 16:34
	 * @param triggerCondition 1
	 * @return: com.alibaba.fastjson.JSONObject
	 */
	private JSONObject handleTriggerCondition(JSONObject triggerCondition){
		JSONObject triggerConditionJsonObject = new JSONObject();
		if (triggerCondition==null) {
			return null;
		}
		// 处理满足所有条件数据
		JSONArray allConditionsTableData = triggerCondition.getJSONArray("allConditionsTableData");
		if (allConditionsTableData!=null&&allConditionsTableData.size()>0) {
			List<ConditionVo> allConditionsTableDataList =
					JSONObject.parseArray(allConditionsTableData.toJSONString(), ConditionVo.class);

			JSONArray finalAllConditionsTable =
					workOrderFilterMenuService.handleFilterCondition(allConditionsTableDataList);
			triggerConditionJsonObject.put("allConditionsTableData",
					finalAllConditionsTable);
		}
		// 处理满足任意条件数据
		JSONArray randomConditionsTableData = triggerCondition.getJSONArray("randomConditionsTableData");
		if (randomConditionsTableData!=null&&randomConditionsTableData.size()>0) {
			List<ConditionVo> randomConditionsTableDataList =
					JSONObject.parseArray(randomConditionsTableData.toJSONString(), ConditionVo.class);

			JSONArray finalrandomConditionsTableData =
					workOrderFilterMenuService.handleFilterCondition(randomConditionsTableDataList);
			triggerConditionJsonObject.put("randomConditionsTableData",
					finalrandomConditionsTableData);
		}
		return triggerConditionJsonObject;
	}
	/**
	 * TODO 根据id查询详情
	 *
	 * @param triggerId 1
	 * @author: victor_tang
	 * @createtime: 2020/1/6 13:50
	 * @return: com.egoo.ews.service.utils.DBResponse
	 */
	@Override
	public DbResponse getDetailById(String triggerId) {
		WorkOrderTriggerInfoVo workOrderTriggerInfo = workOrderTriggerInfoDao.selectByPrimaryKey(triggerId);

		return new DbResponse(ResponseConstant.RES_SUCCESS_CODE,
				ResponseConstant.SELECT_SUCCESS_MSG, workOrderTriggerInfo);
	}

	/**
	 * TODO 获取触发器执行类型一级下拉
	 *
	 * @param triggerTypeCode 1
	 * @author: victor_tang
	 * @createtime: 2020/1/8 14:01
	 * @return: com.egoo.ews.service.utils.DBResponse
	 */
	@Override
	public DbResponse getTriggerActionTypeFirstList(String triggerTypeCode, String tenantId) {

		List<SysDictVo> sysDictVos = sysDictDao.selectListByDictCode(triggerTypeCode,tenantId);
		// 设置标识
		for (SysDictVo sysDictVo : sysDictVos) {
			if (ConstantCode.SysDictCode.SET_STATUS.equals(sysDictVo.getDictCode()) ||
					ConstantCode.SysDictCode.SET_HANDLER.equals(sysDictVo.getDictCode()) ||
					ConstantCode.SysDictCode.SET_PRIORITY.equals(sysDictVo.getDictCode())) {
				// 工单标识
				sysDictVo.setTriggerActionTypeTag(ConstantCode.TriggerActionType.WORK_ORDER);

			} else if (ConstantCode.SysDictCode.PUSH_MSG_CREATER.equals(sysDictVo.getDictCode()) ||
					ConstantCode.SysDictCode.PUSH_MSG_HANDLER.equals(sysDictVo.getDictCode()) ||
					ConstantCode.SysDictCode.PUSH_MSG_SYSUSER.equals(sysDictVo.getDictCode())||
					ConstantCode.SysDictCode.PUSH_MSG_MONITOR.equals(sysDictVo.getDictCode())) {
				// 系统标识
				sysDictVo.setTriggerActionTypeTag(ConstantCode.TriggerActionType.SYSTEM);

			} else if (ConstantCode.SysDictCode.PUSH_INTERFACE.equals(sysDictVo.getDictCode())) {
				// 外部接口推送
				sysDictVo.setTriggerActionTypeTag(ConstantCode.TriggerActionType.EXTERNAL_INTERFACE);

			}
		}

		return new DbResponse(ResponseConstant.RES_SUCCESS_CODE,
				ResponseConstant.SELECT_SUCCESS_MSG,sysDictVos);
	}
	/**
	 * TODO 获取工单触发器执行动作类型二级下拉数据
	 * @author: victor_tang
	 * @createtime: 2020/1/8 14:41
	 * @param triggerTypeCode 1
	 * @return: com.egoo.ews.service.utils.DBResponse
	 */
	@Override
	public DbResponse getTriggerActionTypeSecondList(String triggerTypeCode, String tenantId) {
		// 返回前端数据
		List<InteractiveDataVo> dataList = new ArrayList<InteractiveDataVo>();

		if (ConstantCode.SysDictCode.SET_STATUS.equals(triggerTypeCode)) {
			// 工单状态列表
			dataList = workOrderStatusDao.selectAllWorkOrderStatusName(tenantId);
		}
		else if(ConstantCode.SysDictCode.SET_HANDLER.equals(triggerTypeCode)||
				ConstantCode.SysDictCode.PUSH_MSG_SYSUSER.equals(triggerTypeCode)
				|| ConstantCode.SysDictCode.SEND_MSG_EMPLOYEE.equals(triggerTypeCode)){
			// 部门，角色，用户，二级列表
			dataList = handleUserRoleListData(dataList,tenantId);
		}
		else if(ConstantCode.SysDictCode.SET_PRIORITY.equals(triggerTypeCode)){
			//优先级列表
			dataList = customFieldService
					.selectAllSelectFieldListById(ConstantCode.CustomFieldConstant.PRIORITY_ID);
		}else if(ConstantCode.SysDictCode.SEND_MSG_EMPLOYEE.equals(triggerTypeCode)
				||ConstantCode.SysDictCode.SEND_MSG_CUSTOMER.equals(triggerTypeCode)
				||ConstantCode.SysDictCode.SEND_MSG_CREATOR.equals(triggerTypeCode)
				||ConstantCode.SysDictCode.SEND_MSG_CURRENT_HANDLER.equals(triggerTypeCode)
				||ConstantCode.SysDictCode.SEND_MSG_SENDER.equals(triggerTypeCode)){
			JSONArray templates = eripDataSynService.getTemplate();
//			List<String> strings = JSON.parseArray(templates.toJSONString(), String.class);
			return new DbResponse(ResponseConstant.RES_SUCCESS_CODE,ResponseConstant.SELECT_SUCCESS_MSG, templates);
		}
		return new DbResponse(ResponseConstant.RES_SUCCESS_CODE,ResponseConstant.SELECT_SUCCESS_MSG, dataList);
	}
	/**
	 * TODO 根据工单类型id获取该类型下的所有模板字段信息
	 * @author: victor_tang
	 * @createtime: 2020/1/13 16:19
	 * @param workOrderTypeId 1
	 * @return: com.egoo.ews.service.utils.DBResponse
	 */
	@Override
	public DbResponse getWorkTypeAllFiledInfoByWorkTypeId(String workOrderTypeId) {
		List<WorkOrderTypeFiledVo> workOrderTypeFiledVos = workOrderTypeDao.selectAllFiledByWorkOrderTypeId(Long.valueOf(workOrderTypeId));
		if (workOrderTypeFiledVos==null) {
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,
					"未找到该工单类型相关字段信息");
		}
		List<WorkOrderFieldReflectVo> workOrderFieldReflects = new ArrayList<>();
		for (int i = 0; i < workOrderTypeFiledVos.size(); i++) {
			JSONObject templateContent =
					workOrderTypeFiledVos.get(i).getTemplateContent();

			// 组装工单基础字段
			if (i==0) {
				workOrderFieldReflects =
						assembleWorkOrderFieldReflect(workOrderFieldReflects);
			}
			// 翻译表单模板字段
			workOrderFieldReflects = translateTemplateField(workOrderFieldReflects,
					templateContent,workOrderTypeFiledVos.get(i));
		}
		return new DbResponse(ResponseConstant.RES_SUCCESS_CODE,
				ResponseConstant.SELECT_SUCCESS_MSG,workOrderFieldReflects);
	}
	/**
	 * @Author Donny_Dong
	 * @Description //TODO 组装工单映射字段
	 * @Date 14:00 2019/12/27
	 * @Param [workOrderFieldReflects]
	 * @return void
	 **/
	private List<WorkOrderFieldReflectVo> assembleWorkOrderFieldReflect(List<WorkOrderFieldReflectVo> workOrderFieldReflects) {
		workOrderFieldReflects.add(new WorkOrderFieldReflectVo("title", ConstantCode.WorkOrderBaseFieldMeanig.TITLE,"",""));
		workOrderFieldReflects.add(new WorkOrderFieldReflectVo("externalWorkOrderId",ConstantCode.WorkOrderBaseFieldMeanig.EXTERNAL_WORK_ORDERID,"",""));
		workOrderFieldReflects.add(new WorkOrderFieldReflectVo("accountId",ConstantCode.WorkOrderBaseFieldMeanig.ACCOUNT_ID,"",""));
		workOrderFieldReflects.add(new WorkOrderFieldReflectVo("source",ConstantCode.WorkOrderBaseFieldMeanig.SOURCE,"",""));
		workOrderFieldReflects.add(new WorkOrderFieldReflectVo("priority",ConstantCode.WorkOrderBaseFieldMeanig.PRIORITY,"",""));
		workOrderFieldReflects.add(new WorkOrderFieldReflectVo("channel",ConstantCode.WorkOrderBaseFieldMeanig.CHANNEL,"",""));
		workOrderFieldReflects.add(new WorkOrderFieldReflectVo("clientName",ConstantCode.WorkOrderBaseFieldMeanig.CLIENT_NAME,"",""));
		workOrderFieldReflects.add(new WorkOrderFieldReflectVo("phone",ConstantCode.WorkOrderBaseFieldMeanig.PHONE,"",""));
		workOrderFieldReflects.add(new WorkOrderFieldReflectVo("sex",ConstantCode.WorkOrderBaseFieldMeanig.SEX,"",""));
		workOrderFieldReflects.add(new WorkOrderFieldReflectVo("clientTel",ConstantCode.WorkOrderBaseFieldMeanig.CLIENTTEL,"",""));
		workOrderFieldReflects.add(new WorkOrderFieldReflectVo("cardType",ConstantCode.WorkOrderBaseFieldMeanig.CARDTYPE,"",""));
		workOrderFieldReflects.add(new WorkOrderFieldReflectVo("cardNum",ConstantCode.WorkOrderBaseFieldMeanig.CARDNUM,"",""));
		workOrderFieldReflects.add(new WorkOrderFieldReflectVo("cardAccount",ConstantCode.WorkOrderBaseFieldMeanig.CARDACCOUNT,"",""));
		workOrderFieldReflects.add(new WorkOrderFieldReflectVo("bank",ConstantCode.WorkOrderBaseFieldMeanig.BANK,"",""));
		workOrderFieldReflects.add(new WorkOrderFieldReflectVo("classify",ConstantCode.WorkOrderBaseFieldMeanig.CLASSIFY,"",""));
		workOrderFieldReflects.add(new WorkOrderFieldReflectVo("isSend",ConstantCode.WorkOrderBaseFieldMeanig.ISSEND,"",""));
		workOrderFieldReflects.add(new WorkOrderFieldReflectVo("institution",ConstantCode.WorkOrderBaseFieldMeanig.INSTITUTION,"",""));
		workOrderFieldReflects.add(new WorkOrderFieldReflectVo("problemDesc",ConstantCode.WorkOrderBaseFieldMeanig.PROBLEMDESC,"",""));
		return workOrderFieldReflects;
	}
	/**
	 * @Author Donny_Dong
	 * TODO 翻译模板字段
	 * @Date 13:14 2019/12/27
	 * @Param [formTemplateContent]
	 * @return void
	 **/
	private List<WorkOrderFieldReflectVo> translateTemplateField(List workOrderFieldReflects,
                                                                 JSONObject formTemplateContent, WorkOrderTypeFiledVo workOrderTypeFiledVo) {
		JSONArray jsonArray = formTemplateContent.getJSONArray(ConstantCode.FormTemplateType.LIST);
		for (int i = 0; i <jsonArray.size() ; i++) {
			JSONObject jsonObject = jsonArray.getJSONObject(i);
			if (ConstantCode.FormTemplateType.GRID.equals(jsonObject.getString(ConstantCode.FormTemplateType.TYPE))){
				JSONArray columnsJsonArray = jsonObject.getJSONArray(ConstantCode.FormTemplateType.COLUMNS);
				for (int j = 0; j <columnsJsonArray.size() ; j++) {
					JSONObject jsonObjectColumns = columnsJsonArray.getJSONObject(j);
					JSONArray jsonObjectColumnsArray = jsonObjectColumns.getJSONArray(ConstantCode.FormTemplateType.LIST);
					for (int k = 0; k < jsonObjectColumnsArray.size(); k++) {
						String model = jsonObjectColumnsArray.getJSONObject(k).getString(ConstantCode.FormTemplateType.MODEL);
						String name = jsonObjectColumnsArray.getJSONObject(k).getString(ConstantCode.FormTemplateType.NAME);
						WorkOrderFieldReflectVo workOrderFieldReflect = new WorkOrderFieldReflectVo(model, name, "", "");
						// 添加字段关联关系信息
						workOrderFieldReflect =
								addFiledRelationInfo(workOrderFieldReflect,workOrderTypeFiledVo);
						workOrderFieldReflects.add(workOrderFieldReflect);
					}

				}
			}else {

				String model = jsonObject.getString(ConstantCode.FormTemplateType.MODEL);
				String name = jsonObject.getString(ConstantCode.FormTemplateType.NAME);
				WorkOrderFieldReflectVo workOrderFieldReflect = new WorkOrderFieldReflectVo(model, name, "", "");
				// 添加字段关联关系信息
				workOrderFieldReflect =
						addFiledRelationInfo(workOrderFieldReflect,workOrderTypeFiledVo);
				workOrderFieldReflects.add(workOrderFieldReflect);
			}
		}
		return workOrderFieldReflects;
	}
	/**
	 * TODO
	 * @author: victor_tang
	 * @createtime: 2020/1/13 17:46
	 * @param workOrderFieldReflect 1
	 * @param workOrderTypeFiledVo 2
	 * @return: com.egoo.ews.service.vo.WorkOrderFieldReflect
	 */
	private WorkOrderFieldReflectVo addFiledRelationInfo(WorkOrderFieldReflectVo workOrderFieldReflect, WorkOrderTypeFiledVo workOrderTypeFiledVo){
		if (workOrderTypeFiledVo==null) {
			log.info("工单类型字段映射关系信息为空");
			return workOrderFieldReflect;
		}
		workOrderFieldReflect.setWorkOrderTypeId(workOrderTypeFiledVo.getWorkOrderTypeId()+"");
		workOrderFieldReflect.setWorkOrderTypeNodeId(workOrderTypeFiledVo.getWorkOrderTypeNodeId()+"");
		workOrderFieldReflect.setFormTemplateId(workOrderTypeFiledVo.getTemplateId()+"");
		return workOrderFieldReflect;
	}
	/**
	 * TODO 处理工单状态
	 * @author: victor_tang
	 * @createtime: 2020/1/8 14:55
	 * @param
	 * @return: com.egoo.ews.service.vo.InteractiveData
	 */
	private List<InteractiveDataVo> handleUserRoleListData(List<InteractiveDataVo> dataList, String tenantId){
		// 用户数据组装
		HashMap<String, Object> hashMap = new HashMap<>();
		hashMap.put("tenantId",tenantId);
		InteractiveDataVo userData = new InteractiveDataVo();
		userData.setLabel(ConstantCode.UserRoleDeptType.USER_ZH);
		userData.setValue(ConstantCode.UserRoleDeptType.USER);
		List<InteractiveDataVo> userInteractiveData = ewsUserDao.selectInteractiveUsers(hashMap);
		userData.setChildren(userInteractiveData);

		// 角色数据组装
		InteractiveDataVo roleData = new InteractiveDataVo();
		roleData.setLabel(ConstantCode.UserRoleDeptType.ROLE_ZH);
		roleData.setValue(ConstantCode.UserRoleDeptType.ROLE);
		List<InteractiveDataVo> roleInteractiveData = ewsRoleDao.selectRolesInteractiveByCondition(hashMap);
		roleData.setChildren(roleInteractiveData);

		// 部门数据组装
		InteractiveDataVo deptData = new InteractiveDataVo();
		deptData.setLabel(ConstantCode.UserRoleDeptType.DEPT_ZH);
		deptData.setValue(ConstantCode.UserRoleDeptType.DEPT);
		deptData.setChildren(departmentService.getDepartmentTreeData(tenantId));

		dataList.add(userData);
		dataList.add(roleData);
		dataList.add(deptData);
		return dataList;
	}
	/**
	 * TODO 根据id修改信息
	 *
	 * @param
	 * @author: victor_tang
	 * @createtime: 2020/1/6 13:51
	 * @return: com.egoo.ews.service.utils.DBResponse
	 */
	@Override
	public DbResponse updateById(WorkOrderTriggerInfo workOrderTriggerInfo) {
		workOrderTriggerInfo.setUpdateTime(new Date());

		JSONObject triggerCondition = handleTriggerCondition(workOrderTriggerInfo.getTriggerCondition());

		workOrderTriggerInfo.setTriggerCondition(triggerCondition);
		int result = workOrderTriggerInfoDao.updateByPrimaryKeySelective(workOrderTriggerInfo);

		if (result > 0) {
			return new DbResponse(ResponseConstant.RES_SUCCESS_CODE, ResponseConstant.UPDATE_SUCCESS_MSG);
		}
		return new DbResponse(ResponseConstant.RES_FAIL_CODE, ResponseConstant.UPDATE_FAIL_MSG);
	}

	/**
	 * TODO 根据id删除
	 *
	 * @param triggerId 1
	 * @author: victor_tang
	 * @createtime: 2020/1/6 13:51
	 * @return: com.egoo.ews.service.utils.DBResponse
	 */
	@Override
	public DbResponse deleteById(String triggerId) {
		int result = workOrderTriggerInfoDao.deleteByPrimaryKey(triggerId);
		if (result > 0) {
			return new DbResponse(ResponseConstant.RES_SUCCESS_CODE,
					ResponseConstant.DEL_SUCCESS_MSG);
		}
		return new DbResponse(ResponseConstant.RES_FAIL_CODE,
				ResponseConstant.DEL_FAIL_MSG);
	}
	/**
	 * TODO 根据条件删除触发器
	 * @author: victor_tang
	 * @createtime: 2020/5/12 17:35
	 * @param map 1
	 * @return: com.egoo.ews.service.utils.common.DbResponse
	 */
	@Override
	public DbResponse deleteByConditon(Map<String, Object> map) {
		// 删除触发器
		workOrderTriggerInfoDao.deleteByConditon(map);
		// 删除触发器工单执行记录
		workOrderTriggerRelationDao.deleteByTriggerId(map);
		return new DbResponse(ResponseConstant.RES_SUCCESS_CODE,
				ResponseConstant.DEL_SUCCESS_MSG);
	}
	/**
	 * TODO 批量修改触发器信息
	 *
	 * @param upadteMap 1
	 * @author: victor_tang
	 * @createtime: 2020/1/6 13:51
	 * @return: com.egoo.ews.service.utils.DBResponse
	 */
	@Override
	public DbResponse batchUpdate(Map<String, Object> upadteMap) {

		upadteMap.put("updateTime", new Date());

		int result = workOrderTriggerInfoDao.batchUpdateByPrimaryKeySelective(upadteMap);

		if (result > 0) {
			return new DbResponse(ResponseConstant.RES_SUCCESS_CODE, ResponseConstant.UPDATE_SUCCESS_MSG);
		}
		return new DbResponse(ResponseConstant.RES_FAIL_CODE, ResponseConstant.UPDATE_FAIL_MSG);
	}

}
